package com.eqxiu.ieditor.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eqxiu.ieditor.dto.MallUserDTO;
import eqxiu.passport.sdk.utils.CookieUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @param
 * @author libin
 * @description
 * @date 11:21 2018/1/19
 * @return
 */
public class MallPassport {
    private static final String cookieName = "JSESSIONID";
    private static final String DEFAULT_UA = "eqxiu-internal-mall";
    private static final OkHttpClient client = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS).build();

    public static MallUserDTO getUserInfo(HttpServletRequest servletRequest, String userInfoURL) throws IOException {
        String sessionId = CookieUtils.getCookie(servletRequest, cookieName, null);

        Request request = new Request.Builder().url(userInfoURL).header("Cookie", "JSESSIONID=" + sessionId)
                .header("user-agent", DEFAULT_UA).build();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (responseBody == null) {
            throw new IOException("response body is null");
        }
        JSONObject root = JSON.parseObject(responseBody);
        MallUserDTO mallUserDTO = null;
        if (root.getBoolean("success")) {
            JSONObject jsonObject = root.getJSONObject("map");
            mallUserDTO = root.getObject("obj", MallUserDTO.class);
            if (jsonObject != null && jsonObject.containsKey("beta") && mallUserDTO != null) {
                mallUserDTO.setBeta(jsonObject.get("beta").toString());
            }
        }
        return mallUserDTO;
    }
}
